package notifications

import (
	"context"
	"dash/jwt"
	"encoding/json"
	kithttp "github.com/go-kit/kit/transport/http"
	"github.com/gorilla/mux"
	"net/http"
)

func NewHandler(svc NotificationService) http.Handler {
	getNotificationAlarmCountHandler := kithttp.NewServer(
		makeGetNotificationAlarmCountEndpoint(svc),
		decodeNotificationAlarmCountRequest,
		kithttp.EncodeJSONResponse,
	)

	getNotificationAlarmHandler := kithttp.NewServer(
		makeGetNotificationAlarmEndpoint(svc),
		decodeNotificationAlarmRequest,
		kithttp.EncodeJSONResponse,
	)

	r := mux.NewRouter()
	r.Path("/api/v1/notification/count").Methods("GET").Handler(getNotificationAlarmCountHandler)
	r.Path("/api/v1/notification/alarm").Methods("POST").Handler(getNotificationAlarmHandler)
	return r
}

func decodeNotificationAlarmRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var request getNotificationAlarmRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		return nil, err
	}
	user := r.Context().Value("user").(*jwt.User)
	request.UserId = user.Id
	return request, nil
}

func decodeNotificationAlarmCountRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var request getNotificationAlarmCountRequest
	user := r.Context().Value("user").(*jwt.User)
	request.UserId = user.Id
	return request, nil
}

type getNotificationAlarmRequest struct {
	Size   int `json:"size"`
	UserId string
	Data   Alarm `jon:"data"`
}

type getNotificationAlarmResponse struct {
	Data  []Alarm `json:"data"`
	Error string  `json:"error,omitempty"`
}

type getNotificationAlarmCountRequest struct {
	UserId string
}

type getNotificationAlarmCountResponse struct {
	Count int    `json:"count"`
	Error string `json:"error,omitempty"`
}
